<?php

class AdbTable extends Adb
{

  protected static $instances = array();

  /**
   * 
   * @return AdbTable
   */
  public static function getInstance($table)
  {
    if (empty(self::$instances[$table])) {
      self::$instances[$table] = new AdbTable($table);
    }

    return self::$instances[$table];
  }

  protected function __construct($name)
  {
    parent::__construct($name);
  }

  public function getFields()
  {
    return $this->manager()->listTableFields($this->getName());
  }

  public function getField($name)
  {
    $field = new AdbField($this, $name);
    return $field;
  }

  public function getPrimaryKey()
  {
    return $this->getName() . '_id';
  }

  public function exists()
  {
    $tables = $this->manager()->listTables();
    return in_array($this->getName(), $tables);
  }

  public function create()
  {
    $pk = $this->getPrimaryKey();

    $fields = array(
      $pk => array (
        'type' => 'integer',
        'length' => 8,
        'unsigned' => 1,
        'notnull' => 1,
        'autoincrement' => 1
      )
    );

    $options = array(
      'charset' => 'utf8',
      'collate' => 'utf8_unicode_ci'
    );

    $this->manager()->createTable($this->getName(), $fields, $options);

    $definition = array (
      'primary' => true,
      'fields' => array (
        $pk => array()
      )
    );

    $this->manager()->createConstraint($this->getName(), 'PRIMARY', $definition);
  }

  public function rename($name)
  {
    $this->manager()->alterTable($this->getName(), array('name' => $name), false);
    $this->name = $name;
  }

  public function remove()
  {
    $this->manager()->dropTable($this->getName());
  }

}
